package com.sk.weichat.ui.groupchat;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.makeramen.roundedimageview.RoundedImageView;
import com.sk.weichat.R;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.okhttp.GsonHelper;
import com.sk.weichat.okhttp.OkHttpHelper;
import com.sk.weichat.okhttp.callback.ResultCallback;
import com.sk.weichat.okhttp.request.RequestParams;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.message.multi.EventGroupStatus;
import com.sk.weichat.util.CameraUtil;
import com.sk.weichat.util.PermissionUtil;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.SelectPhotoBottomDialog;
import com.sk.weichat.view.TipDialog;
import com.suke.widget.SwitchButton;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * @Author: chenzl
 * @ClassName: SetOpenGroupActivity
 * @Description: 设置公开群
 * @CreateDate: 2019/9/17 11:44
 */
public class SetOpenGroupActivity extends BaseActivity implements View.OnClickListener, PermissionUtil.OnRequestPermissionsResultCallbacks{

    private static final int REQUEST_CAMERA_CODE = 1001;
    private static final int REQUEST_CODE_CAPTURE_CROP_PHOTO = 1;
    private static final int REQUEST_CODE_PICK_CROP_PHOTO = 2;
    private static final int REQUEST_CODE_CROP_PHOTO = 3;

    private RoundedImageView mAvatarImg;
    private TextView tvGroupHeadTips;
    private SwitchButton sbOpenGroup;
    private Button btnOpenGroup;

    private SelectPhotoBottomDialog mSelectPhotoBottomDialog;
    private Uri mNewPhotoUri;
    private File mCurrentFile;

    private String RoomJid;
    private String RoomId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_open_group);
        getSupportActionBar().hide();

        RoomJid = getIntent().getStringExtra("RoomJid");
        RoomId = getIntent().getStringExtra("RoomId");
        initView();
    }

    private void initView(){
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = findViewById(R.id.tv_title_center);
        tvTitle.setText(getString(R.string.tips_set_open_group));

        mAvatarImg = findViewById(R.id.avatar_img);
        mAvatarImg.setImageResource(R.mipmap.bg_def_open_group);


        tvGroupHeadTips = findViewById(R.id.tv_group_head_tips);
        sbOpenGroup = findViewById(R.id.sb_open_group);
        btnOpenGroup = findViewById(R.id.btn_open_group);
//        sbOpenGroup.setChecked(true);
        sbOpenGroup.setEnabled(false);
        mAvatarImg.setOnClickListener(this);
        btnOpenGroup.setOnClickListener(this);
        sbOpenGroup.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked && mCurrentFile!=null){
                    btnOpenGroup.setEnabled(true);
                    btnOpenGroup.setBackgroundResource(R.drawable.bg_border_btn_blue);
                }else {
                    btnOpenGroup.setEnabled(false);
                    btnOpenGroup.setBackgroundResource(R.drawable.bg_border_btn_gray);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {

        if (v==mAvatarImg){
            mSelectPhotoBottomDialog = new SelectPhotoBottomDialog(SetOpenGroupActivity.this, new SelectPhotoBottomDialog.OnBottomDialogClickListener() {
                @Override
                public void onClickPhoto() {
                    selectPhoto();
                    mSelectPhotoBottomDialog.dismiss();
                }

                @Override
                public void onClickcamera() {
                    boolean isReadContacts = PermissionUtil.checkSelfPermissions(SetOpenGroupActivity.this, new String[]{Manifest.permission.CAMERA});
                    if (isReadContacts) {
                        takePhoto();
                    } else {
                        PermissionUtil.requestPermissions(SetOpenGroupActivity.this, 0x01, new String[]{Manifest.permission.CAMERA});
                    }
                    mSelectPhotoBottomDialog.dismiss();
                }

                @Override
                public void onClickCancle() {
                    mSelectPhotoBottomDialog.dismiss();
                }
            });
            mSelectPhotoBottomDialog.show();
        }else if (v==btnOpenGroup){
            uploadAvatar(mCurrentFile);
        }
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        mNewPhotoUri = CameraUtil.getOutputMediaFileUri(this, CameraUtil.MEDIA_TYPE_IMAGE);
        CameraUtil.captureImage(this, mNewPhotoUri, REQUEST_CODE_CAPTURE_CROP_PHOTO);
    }

    /**
     * 相册选择
     */
    private void selectPhoto() {
        CameraUtil.pickImageSimple(this, REQUEST_CODE_PICK_CROP_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_CAPTURE_CROP_PHOTO) {// 拍照返回再去裁减
            if (resultCode == Activity.RESULT_OK) {
                if (mNewPhotoUri != null) {
                    Uri o = mNewPhotoUri;
                    mNewPhotoUri = CameraUtil.getOutputMediaFileUri(this, CameraUtil.MEDIA_TYPE_IMAGE);
                    mCurrentFile = new File(mNewPhotoUri.getPath());
                    CameraUtil.cropImage(this, o, mNewPhotoUri, REQUEST_CODE_CROP_PHOTO, 1, 1, 300, 300);
                } else {
                    ToastUtil.showToast(this, R.string.c_photo_album_failed);
                }
            }
        } else if (requestCode == REQUEST_CODE_PICK_CROP_PHOTO) {// 选择一张图片,然后立即调用裁减
            if (resultCode == Activity.RESULT_OK) {
                if (data != null && data.getData() != null) {
                    Uri o = data.getData();
                    mNewPhotoUri = CameraUtil.getOutputMediaFileUri(this, CameraUtil.MEDIA_TYPE_IMAGE);
                    mCurrentFile = new File(mNewPhotoUri.getPath());
                    CameraUtil.cropImage(this, o, mNewPhotoUri, REQUEST_CODE_CROP_PHOTO, 1, 1, 300, 300);
                } else {
                    ToastUtil.showToast(this, R.string.c_photo_album_failed);
                }
            }
        } else if (requestCode == REQUEST_CODE_CROP_PHOTO) {
            if (resultCode == Activity.RESULT_OK) {
                if (mNewPhotoUri != null) {
                    mCurrentFile = new File(mNewPhotoUri.getPath());
                    tvGroupHeadTips.setVisibility(View.GONE);
                    AvatarHelper.getInstance().displayUrl(mNewPhotoUri.toString(), mAvatarImg);
                    if (sbOpenGroup.isChecked() && mCurrentFile.exists()){
                        btnOpenGroup.setEnabled(true);
                        btnOpenGroup.setBackgroundResource(R.drawable.bg_border_btn_blue);
                    }else {
                        btnOpenGroup.setEnabled(false);
                        btnOpenGroup.setBackgroundResource(R.drawable.bg_border_btn_gray);
                    }
                    // 上传头像
//                    uploadAvatar(mCurrentFile);
                } else {
                    ToastUtil.showToast(this, R.string.c_crop_failed);
                }
            }
        }else if (requestCode == REQUEST_CAMERA_CODE) {
            boolean isReadContacts = PermissionUtil.checkSelfPermissions(SetOpenGroupActivity.this, new String[]{Manifest.permission.CAMERA});
            if (isReadContacts) {
                takePhoto();
            }
        }
    }


    /**
     * @author: czl
     * @description 上传群头像
     * @date: 2019/9/16 18:16
     */
    private void uploadAvatar(File file) {
        if (!file.exists()) {
            // 文件不存在
            return;
        }
        // 显示正在上传的ProgressDialog
        DialogHelper.showDefaulteMessageProgressDialog(this);
        RequestParams params = new RequestParams();
        params.put("access_token",coreManager.getSelfStatus().accessToken);
        params.put("roomId", RoomId);
        try {
            params.put("groupHeads", file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        params.put("isLook","0");
        OkHttpHelper okHttpHelper = new OkHttpHelper();
        okHttpHelper.MultiPostRequest(coreManager.getConfig().ROOM_GROUP_HEADS, params, new ResultCallback() {
            @Override
            public void onSuccess(Object result) {
                DialogHelper.dismissProgressDialog();
                int resultCode = GsonHelper.GsonToInt(result.toString(),"resultCode");
                if (resultCode==1){
                    AvatarHelper.getInstance().updateAvatar(RoomJid);// 更新时间
                    EventBus.getDefault().post(new EventGroupStatus(111111, 0));//通知群列表刷新
                    //通知消息列表刷新
                    MsgBroadcast.broadcastMsgUiUpdate(getApplicationContext());
                    ToastUtil.showToast(mContext,getString(R.string.tips_set_outward_group_success));
                    finish();

                }else {
                    ToastUtil.showToast(mContext,GsonHelper.GsonToString(result.toString(),"resultMsg"));
                }
            }

            @Override
            public void onFailure(Object result) {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showToast(mContext, R.string.tips_set_outward_group_err);
            }
        });
     /*   AsyncHttpClient client = new AsyncHttpClient();
        client.post(coreManager.getConfig().ROOM_GROUP_HEADS, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
                DialogHelper.dismissProgressDialog();
                boolean success = false;
                if (arg0 == 200) {
                    Result result = null;
                    try {
                        result = JSON.parseObject(new String(arg2), Result.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (result != null && result.getResultCode() == Result.CODE_SUCCESS) {
                        success = true;
                    }
                }

                if (success) {
                    AvatarHelper.getInstance().updateAvatar(RoomJid);// 更新时间
                    EventBus.getDefault().post(new EventGroupStatus(111111, 0));//通知群列表刷新
                    //通知消息列表刷新
                    MsgBroadcast.broadcastMsgUiUpdate(getApplicationContext());
                    ToastUtil.showToast(mContext,getString(R.string.tips_set_outward_group_success));
                    finish();

                } else {
                    ToastUtil.showToast(mContext, R.string.tips_set_outward_group_err);
                }
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showToast(mContext, R.string.tips_set_outward_group_err);
            }
        });*/
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms, boolean isAllGranted) {
        if (isAllGranted) {// 请求权限返回 已全部授权
            takePhoto();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms, boolean isAllDenied) {
        boolean onceAgain = PermissionUtil.deniedRequestPermissionsAgain(this, perms.toArray(new String[perms.size()]));
        if (onceAgain) {
            TipDialog mTipDialog = new TipDialog(this);
            mTipDialog.setmConfirmOnClickListener(getString(R.string.tip_reject_permission_place_holder, getString(R.string.permission_photo)), new TipDialog.ConfirmOnClickListener() {
                @Override
                public void confirm() {
                    PermissionUtil.startApplicationDetailsSettings(SetOpenGroupActivity.this, REQUEST_CAMERA_CODE);
                }
            });
            mTipDialog.show();
        } else {
            ToastUtil.showToast(SetOpenGroupActivity.this, getString(R.string.tip_permission_reboot_place_holder, getString(R.string.permission_photo)));
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}
